package com.bawei.movie.view


import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.movie.R
import com.bawei.movie.adapter.MoviePagingDataAdapter
import com.bawei.movie.databinding.FragmentMovieListBinding
import com.bawei.movie.viewmodel.MovieViewModel
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_MOVIE_LIST)
class MovieListFragment : BaseMviFragment<FragmentMovieListBinding>() {

    private val mViewModel: MovieViewModel by activityViewModels()
    private lateinit var movieAdapter: MoviePagingDataAdapter
    private lateinit var mRecyclerView: RecyclerView

    @Autowired
    @JvmField
    var tabId: Int = -1


    override fun getLayoutId(): Int = R.layout.fragment_movie_list

    override fun initViews() {
        ARouter.getInstance().inject(this)

        mRecyclerView = mDataBinding.rvMovie
        mRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
        movieAdapter = MoviePagingDataAdapter()
        mRecyclerView.adapter = movieAdapter

        //Item的点击事件
        movieAdapter.setItemClickListener(object : MoviePagingDataAdapter.ItemClickListener{
            override fun onItemChildClick(v: View, position: Int, entity: MovieVideoEntity) {
               ARouter.getInstance().build(RoutePath.PATH_DETAIL_PAGE).withSerializable("movieEntity", entity).navigation()
            }
        })

        //下拉刷新事件
        mDataBinding.refreshLayout.setOnRefreshListener {
            movieAdapter.refresh()
        }

        //优化RecyclerView
        mRecyclerView.setHasFixedSize(true) //固定的ItemView大小
        mRecyclerView.isNestedScrollingEnabled = false //嵌套禁止滚动
        mRecyclerView.setItemViewCacheSize(20) //缓存ItemView的数量

        //创建缓存池
        var cachePool = RecyclerView.RecycledViewPool().apply {
            setMaxRecycledViews(0, 5) //ViewType类型必须和数据适配器中ItemType一致
        }
        mRecyclerView.setRecycledViewPool(cachePool)

        //取消不需要的动画
        (mRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

        //控制列表图片加载时机
        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    Glide.with(this@MovieListFragment).resumeRequests()
                }else{
                    Glide.with(this@MovieListFragment).pauseRequests()
                }
            }
        })

        //加载数据
        loadDataWithPaging(tabId)
    }

    private fun loadDataWithPaging(tabId: Int) {
        lifecycleScope.launch {
            if (tabId == -1){
                mViewModel.loadRecommendVideo().collectLatest {
                    if (mDataBinding.refreshLayout.isRefreshing){
                        mDataBinding.refreshLayout.finishRefresh()
                    }
                    movieAdapter.submitData(it)
                }
            }else{
                mViewModel.loadMutilVideoById(tabId).collectLatest {
                    if (mDataBinding.refreshLayout.isRefreshing){
                        mDataBinding.refreshLayout.finishRefresh()
                    }
                    movieAdapter.submitData(it)
                }
            }
        }
    }



}